package com_.dxy_test_.thread_pool_;

import cn.hutool.core.date.LocalDateTimeUtil;

import java.time.LocalDateTime;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @Description 测试延迟或者周期线程池
 * @Author dangxianyue
 * @Date 2024/3/9 11:24
 */
public class ScheduledThreadPoolTest {

    private final ScheduledExecutorService executor;


    public ScheduledThreadPoolTest() {
        // init executorService
        final int corePoolSize = 1;// 核心线程数
        this.executor = new ScheduledThreadPoolExecutor(corePoolSize, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                thread.setName("my scheduled thread pool");
                return thread;
            }
        });
    }

    public void test_schedule() {
        // 延迟 1 秒后执行任务（没有周期性）
        executor.schedule(new MyTask(), 1, TimeUnit.SECONDS);
    }


    public void test_scheduleAtFixedRate() {
        // 延迟 2 秒后开始，每隔 3 秒执行一次任务
        executor.scheduleAtFixedRate(new MyTask(), 2, 3, TimeUnit.SECONDS);
    }

    public void test_scheduleWithFixedDelay() {
        // 延迟 3 秒后开始，每次执行结束后延迟 2 秒再次执行任务
        executor.scheduleWithFixedDelay(new MyTask(), 3, 2, TimeUnit.SECONDS);
    }

    // 关闭线程池
    public void shutdownThreadPool() {
        executor.shutdown();
    }



    public class MyTask implements Runnable {

        @Override
        public void run() {
            System.out.println(LocalDateTimeUtil.format(LocalDateTime.now(), "HH:mm:ss") + " 执行任务……");
        }
    }


    public static void main(String[] args) {
        final ScheduledThreadPoolTest scheduledThreadPool = new ScheduledThreadPoolTest();

        // scheduledThreadPool.test_schedule();
        // scheduledThreadPool.test_scheduleAtFixedRate();
        scheduledThreadPool.test_scheduleWithFixedDelay();


        // 主线程等待任务执行完成
        try {
            Thread.sleep(20000); // 等待足够长的时间，以便观察任务执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        scheduledThreadPool.shutdownThreadPool();
    }
}
